/*
 *	settings-view view
 *  -----------------------------------------------------------------------------------------------------------
 */

site.view('settings-view', {
	
	onLoad: function(settings) {
		this.startAll(settings);
	},
	
	onUnload: function() {
		this.stopAll();
	}

})

/*
 *	settings main view manager (internal navigation) module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('main_view_manager', function(context) {
	var query = context.query,
		request	= context.request,
		require = context.require,
		tipsy = require('tipsy'),
		livequery = require('livequery'),

		processing = false,
		contentContainer,
		internalActions,
		rLastUrlPart = /[^\/]*$/,
		currentModuleView = '',

		onMenuClick = function(e) {
			var anchor = $(this),
	       		action = anchor.attr('href'),
	       		old_content_height = contentContainer.innerHeight(),
	       	 	old_content = contentContainer.children('div'),
	       	 	urlName = anchor.find('.mini_name').text(),
	       	 	

	       	 	actionName = action.substring(action.indexOf('settings'))
								   .replace('settings/', '')
								   .replace('settings', '')
								   .split('/');
       
			if (!$(this).children('div').hasClass('active') && !processing) {
				processing = true;

				$('#content > aside .list_main_container').removeClass('active');
				$(this).children('div').addClass('active');

				request({
				    url: action,
				    dataType: 'json',
				    cache: false,
				    success: function(json) {             
				        contentContainer.css({'height':old_content_height + 'px',
				                               'overflow':'hidden'});

				        var new_content = old_content.after(json.content).next('div'),              
				       		new_content_height = new_content.innerHeight(),
				        	animation_time = 700;
				        
				        old_content.children('.header_menu')
				                   .css('position','relative')
				                   .next('div')
				                   .css('padding-top','0px');
				      
				       	// Load new view module (and inform about change) 
				        context.trigger(currentModuleView[0] + 'ViewUnloaded', currentModuleView.slice(1));
				        context.trigger(actionName[0] + 'ViewLoaded', actionName.slice(1));
				        currentModuleView = actionName;
				        
				        old_content.animate({'margin-top': -old_content_height +'px'},animation_time,function() {
    
				            $(this).remove();
				        });

				        contentContainer.animate({'height': new_content_height + 'px'},animation_time,function() {
				            $('#content > section').css('height','auto')
				                                    .children('div')
				                                    .children('.header_menu')
				                                    .css('position','absolute')
				                                    .next('div')
				                                    .css('padding-top','47px');

				            processing = false;
				            window.history.pushState(urlName, urlName, anchor.attr('href'));
				        });        
				    }
				});      
			}
       		e.preventDefault();
       		return false;
    
		};

	return {

		init: function(settings) {
			contentContainer = query('#content > section');
			internalActions = query('.internal_action');

			internalActions.on('click', onMenuClick);

			// init default view (from url)
			
			var href = document.location.href;
			currentModuleView = href.substring(href.indexOf('settings'))
									.replace('settings/', '')
									.replace('settings', '')
									.split('/');

			currentModuleView = currentModuleView[0] !== '' ? currentModuleView : ['desktop'] ;
			context.trigger(currentModuleView[0] + 'ViewLoaded', currentModuleView.slice(1));

			// tipsy forms		
			livequery.init('input, textarea', function() {
				tipsy.init(this, {
					gravity: query(window).width() < 1260 ? 's' : 'w',
					trigger: 'focus'
				})
			});

			// tipsy actions
			livequery.init('.tooltip', function(){
        		this.tipsy({gravity:'se'});
    		});		
		},

		destroy: function() {
			internalActions.off(onMenuClick);
		}

	}

})

/*
 *	settings desktop view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('desktop_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		fileUploader = require('FileUploader'),
		iphoneSwitch = require('switch'),
		colorPicker = require('colorPicker'),
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),

		uploadUserWallpaper = function() {
			if(!context.getElementById('user_wallpaper'))
        		return;
    
   			var uploader = fileUploader.create({
	                element: context.getElementById('user_wallpaper'),
	                action: '/settings/upload_wallpaper',
	                name: 'user_wallpaper',
	                allowedExtensions: ['png','jpg','jpeg'],        
	                sizeLimit: 2*1024*1024,
	                multiple: false,
	                onComplete: function(id, fileName, responseJSON) {

	                    if(responseJSON.success === true) {
	                      
	                        var oldImage = $('#screen_wallpaper > img');
	                        if (oldImage.size()){
	                            $('#screen_wallpaper').prepend('<img src="' + responseJSON.message + '" alt="" />')
	                        } else {
	                            $('#screen_wallpaper').prepend('<img src="' + responseJSON.message + '"  style="display: none" alt="" />').children('img').fadeIn(3000); 
	                        }
	                         
							oldImage.fadeOut(1000,function(){$(this).remove()});
							$('#delete_user_wallpaper').css('display','block');
	               
	                    }
	                }
            });

		},

		deleteUserWallpaper = function() {
		    $('#delete_user_wallpaper').on('click', function(event){
		        var button = $(this),
		        	wallpaper =  $(this).prevAll('img'),
		        	action = $(this).attr('href');
		        
		        request({
	                url: action,
	                dataType: 'json',
	                success: function(json){
	                    wallpaper.fadeOut(2000, function(){wallpaper.remove()});
	                    button.css('display','none');
	                }
		        });
		        event.preventDefault();
		    })
		};

	return {
		events: {

			desktopViewLoaded: function(subView) {
				console.log('desktop loaded');
				uploadUserWallpaper();
				deleteUserWallpaper();
				
				// iphone switch init
				iphoneSwitch.init('#grid', {
					onChange: function(toggle) {
						toggle ? $('#screen_grid').fadeIn() : $('#screen_grid').fadeOut(); 
					}
				});

				// colorpicker init
				colorPicker.init('#color', {
					onSubmit:  function(hsb, hex, rgb, el) {
						this.val(hex);
                        $('#screen_color').animate({backgroundColor: '#' + hex});
                        this.ColorPickerHide();
					},
					onBeforeShow: function () {
						this.ColorPickerSetColor(this.val());
					}
				});

				// submit form
				
				ajaxSubmitForm.init('.standard_form',{
					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });  
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					}
				});
				
			},

			desktopViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.standard_form');
			}
		}
	}
})

/*
 *	settings profile view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('profile_view_manager', function(context) {
	var query = $ = context.query,
		request	= context.request,
		processing = false,
    	headerMenu,
    	rLastUrlPart = /[^\/]*$/,
    	animation_time = 700,
    	currentModuleView,
    
   		headerMouseClick = function(e) {
	        
	        var contentContainer = $('#content > section > div'),
	        	anchor = $(this);
	        	action = anchor.attr('href'),
	               
	        	old_content = contentContainer.children('div'),
	        	old_content_height = old_content.innerHeight(),
	        	actionName = action.match(rLastUrlPart),
	        	urlName = anchor.text();

	       	if (!anchor.hasClass('active') && !processing) {
	           
	           processing = true;
	           $('.header_menu a').removeClass('active');
	           anchor.addClass('active');
	           
	           request({
	                url: action,
	                dataType: 'json',
	                cache: false,
	                success: function(json) { 
	                    contentContainer.css({
	                    	'height': old_content_height + 'px',
	                        'overflow':'hidden'
	                    });
	                                       
	                    var new_content = old_content.after(json.content).next('div'),              
	                    	new_content_height = new_content.innerHeight();

	                    	// Load new view module (and inform about change) 
				        	context.trigger(currentModuleView + 'ProfileViewUnloaded');
				       		context.trigger(actionName + 'ProfileViewLoaded');
				        	currentModuleView = actionName;

	                    old_content.animate({'margin-top': -old_content_height + 47 +'px'},animation_time,function() {
	                        contentContainer.children('.header_menu')
	                                   .css('position','absolute');
	                        $(this).remove();
	                    });
	                    
	                    contentContainer.animate({'height': new_content_height + 47 + 'px'},animation_time,function() {
	                        $('#content > section > div').css('height','auto')
	                                                      .children('div')
	                                                      .css('padding-top','47px');
	                        processing = false;
	                        window.history.pushState(urlName, urlName, anchor.attr('href'));
	                    });     
	                }
	            });
	       	}
	        e.preventDefault();
	        return false;
	    };

	return {
		events: {

			profileViewLoaded: function(subView) {
				console.log('profile loaded');
				headerMenu =  $('.header_menu a');

				headerMenu.on('click', headerMouseClick);
				if(subView && subView[0] === 'profile' || subView[0] === '' || subView.length === 0) {
					currentModuleView = 'profile';
				} else {
					currentModuleView = subView[0];
				}
				context.trigger(currentModuleView + 'ProfileViewLoaded');
			},

			profileViewUnloaded: function(subView) {
				headerMenu.off('click', headerMouseClick);
				context.trigger(currentModuleView + 'ProfileViewUnloaded');
			}
		}
	}
})

.module('profile_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util,
		fileUploader = require('FileUploader'),
		multiselect = require('multiselect'),
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),
		datepicker = require('datepicker'),
		autocomplete = require('autocomplete'),

		uploadUserPhoto = function() {
 			if(!context.getElementById('user_photo'))
        		return;
    
        	var uploader = fileUploader.create({
	                element: context.getElementById('user_photo'),
	                action: '/settings/upload_user_photo',
	                name: 'user_photo',
	                allowedExtensions: ['png','jpg','jpeg'],        
	                sizeLimit: 2*1024*1024,
	                multiple: false,
	                onComplete: function(id, fileName, responseJSON){

						if(responseJSON.success === true){
							var oldImage = $('#user_photo_container > img');
							$('#user_photo_container').prepend('<img src="' + responseJSON.message + '" alt="" />')
							oldImage.fadeOut(1000,function(){$(this).remove()}).next('a').css('display','block');
						}
	                }
            });
		},

		deleteUserPhoto = function(event) {
		    $('#delete_user_photo').on('click', function(event){
		        var button = $(this),
		        	photo =  $(this).prevAll('img'),
		        	action = $(this).attr('href');

		        request({
	                url: action,
	                dataType: 'json',
	                success: function(json){
	                    $('#user_photo_container').prepend('<img src="/public/application/images/default_profile_image.png" alt="" />');
	                    photo.fadeOut(2000, function(){photo.remove()});
	                    button.css('display','none');
	                }
		        });
		        event.preventDefault();
		    })      
		};

	return {
		events: {

			profileProfileViewLoaded: function(subView) {
				console.log('profile sub loaded');
				uploadUserPhoto();
				deleteUserPhoto();

				// multiselect init
				multiselect.init('#field');

				// datepicker
				datepicker.init('#birth_date');

				// ajax submit form init
				ajaxSubmitForm.init('.standard_form',{

					mapInputFields: {
						'field': 'standard_select_form0',
						'address': 'textboxlist'
					},

					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					}
				});

				// autocomplete place init
				autocomplete.init('#address', {
					url: '/settings/get_locality'
				});
			},

			profileProfileViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.standard_form');
			}
		}
	}
})

.module('experience_view', function(context) {
	var query = context.query,
		require = context.require,
		request = context.request,
		iphoneSwitch = require('switch'),
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),
		actionDialog = require('actionDialog'),
	
		switchInit = function() {
			iphoneSwitch.init(query('.still:checkbox').not('.iPhoneCheckContainer .still:checkbox'), {
				onChange: function(toggle) {
					toggle ? this.closest('li').prev('li').slideUp() : this.closest('li').prev('li').slideDown();
				}
			});
		}

	return {
		events: {
			experienceProfileViewLoaded: function(subView) {
				console.log('experience sub loaded');

				switchInit();

				// ajax submit form init
				ajaxSubmitForm.init('.experience_form',{

					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });

                        if(data.action == 'add') {
							this.next('header').next('ul').append(data.content).children('li:last-child').css('display','none').slideDown();
							this[0].reset();
						} else {
							this.closest('li').html(data.content);                                
						}

						switchInit();
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					},

					getSuffixVal: function() {
						var el = this.find('input[name=experience_id]');

						if(el.length > 0) {
							return '_' + el.val();
						} else {
							return '';
						}
					}
				});

				// delete actions
				actionDialog.create('.delete', function(el) {
					var anchor = el,
			        	action = anchor.attr('href');
			        
			        request({
			            url: action,
			            dataType: 'json',
			            success: function(json) {
			                anchor.parents('li').slideUp().remove();
			            }
			        });
				});

			},

			experienceProfileViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.experience_form');
			}
		}
	}
})

.module('education_view', function(context) {
	var query = context.query,
		require = context.require,
		request = context.request,
		iphoneSwitch = require('switch'),
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),
		actionDialog = require('actionDialog'),
		
		switchInit = function() {
			iphoneSwitch.init(query('.still:checkbox').not('.iPhoneCheckContainer .still:checkbox'), {
				onChange: function(toggle) {
					toggle ? this.closest('li').prev('li').slideUp() : this.closest('li').prev('li').slideDown();
				}
			});
		};


	return {
		events: {
			educationProfileViewLoaded: function(subView) {
				console.log('education sub loaded');
	
				switchInit();

				// ajax submit form init
				ajaxSubmitForm.init('.education_form',{

					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });

                        if(data.action == 'add') {
							this.next('header').next('ul').append(data.content).children('li:last-child').css('display','none').slideDown();
							this[0].reset();
						} else {
							this.closest('li').html(data.content);                               
						}

						switchInit();
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					},

					getSuffixVal: function() {
						var el = this.find('input[name=education_id]');

						if(el.length > 0) {
							return '_' + el.val();
						} else {
							return '';
						}
					}
				});

				// delete actions
				actionDialog.create('.delete', function(el) {
					var anchor = el,
			        	action = anchor.attr('href');
			        
			        request({
			            url: action,
			            dataType: 'json',
			            success: function(json) {
			                anchor.parents('li').slideUp().remove();
			            }
			        });
				})

			},

			educationProfileViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.education_form');
			}
		}
	}
})

.module('elements_edit', function(context) {
	var query = context.query,

		init = function() {

			query('#content').on('click', '.edit', function(e) {

				var all_edit_action = query('.edit'),
					anchor = query(this),
					container = anchor.parent().parent();

				if (container.hasClass('active')) {
				    container.next('form').slideUp(500, function() {
				        container.removeClass('active');
				    });
				} else {
				   var all_active = all_edit_action.parents('.active');          
				   all_active.next('form').slideUp(500,function(){all_active.removeClass('active')});
				             
				   container.addClass('active').next('form').slideDown(500);  
				} 

				e.preventDefault();
	    	});
		},

		destroy = function() {
			query('#content').off('click', '.edit');
		}

	return {
		events: {
			educationProfileViewLoaded: init,
			experienceProfileViewLoaded: init,

			educationProfileViewUnloaded: destroy,
			experienceProfileViewUnloaded: destroy
		}
	}
})

.module('additional_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify');

	return {
		events: {
			additionalProfileViewLoaded: function(subView) {
				console.log('additional sub loaded');

				// ajax submit form init
				ajaxSubmitForm.init('.standard_form',{
					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });  
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					}
				});
			},

			additionalProfileViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.standard_form');
			}
		}
	}
})

/*
 *	settings privacy view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('privacy_view', function(context) {
	var require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify');

	return {
		events: {

			privacyViewLoaded: function(subView) {
				console.log('privacy loaded');

				// ajax submit form init
				ajaxSubmitForm.init('.standard_form',{
					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });  
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					}
				});
			},

			privacyViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.standard_form');
			}
		}
	}
})

/*
 *	settings accoount view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('account_view', function(context) {
	var require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify');

	return {
		events: {

			accountViewLoaded: function(subView) {
				console.log('account loaded');

				ajaxSubmitForm.init('.standard_form',{
					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });  
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					}
				});
			},

			accountViewUnloaded: function(subView) {
				ajaxSubmitForm.destroy('.standard_form');
			}
		}
	}
})